<?php
// 应用公共文件
namespace app;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

class Common {

    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    //下载csv文件
    static function downCsv($fileName, $csvBody) {


    }


    /**
     *name:导出对账失败的结果
     * log: 2018/12/21 0021
     * Author:long
     */
    static function order_query_csv($header,$data,$fileName) {
        // 处理头部标题
        $header = implode(',', $header) . PHP_EOL;
        $content = '';

        foreach ($data as $row) {
            $content.=implode(",",array_values($row)).PHP_EOL;
        }

        // 拼接
        $csv = $header . $content;
        Common::downCsv($fileName.".csv", $csv);
    }

    //一种导出csv的方式
    //标题，表头，内容，汇总或table foot
    static function excel_csv($head,$cols,$data,$foot=[],$sumArray=['total'],$filename){
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename . ".xls");

        //实例数据
        //'送货单号','出货时间','图纸编号 Item','品名规格 Specs','数量 Qty','单位 Unit','单价 Price(USD)','金额 Amount','备注''

        $str = '';
        //header_line，所有表头数据都拼接，用，和\n换行
        foreach($head as $row){
            $str .= '"' . implode('"' . "\t" . '"', $row) . '"' . "\n";
        }

        //halt($head,$cols);exit;
               
        $sum=0;
        foreach ($data as $row) {
            foreach($cols as $index=>$col){
                if($col=='index')
                    $str .= '"'.($index+1). '"' . "\t"; //序号
                elseif($col!='')
                    $str .= '"' . $row[$col].'"' . "\t";    //输出字段
                else 
                    $str .= "\t";                           //输出空格
            }
            $str .="\n";
            if($sumArray) $sum += $row['total'];
        }


        if($sum>0) $sumArray[] = $sum;
        
        //$foot[]=$sumArray; "\t"

        //var_dump($foot);
        foreach($foot as $row){
            $str .= $row;
        }

        $str = mb_convert_encoding($str, "gb2312", "utf-8");
        echo $str;
        exit;
    }



/**
 * 导出excel(csv)
 * @data 导出数据
 * @headlist 第一行,列名
 * @fileName 输出Excel文件名
 */

static function csv_export($data = array(), $headlist = array(), $fileName) {

     header('Content-Type: application/vnd.ms-excel');
     header('Content-Disposition: attachment;filename='.$fileName.'.csv"');
     header('Cache-Control: max-age=0');

    //打开PHP文件句柄,php://output 表示直接输出到浏览器
    $fp = fopen('php://output', 'a');

    //输出Excel列名信息
    foreach ($headlist as &$value) {
        //CSV的Excel支持GBK编码，一定要转换，否则乱码
        $value = iconv('utf-8', 'GBK//IGNORE', $value);
    }

    //将数据通过fputcsv写到文件句柄
    fputcsv($fp, $headlist);  

    foreach($data as $row){
        foreach($row as &$value){
            $value = iconv('utf-8', 'GBK//IGNORE', $value);
            //$value = mb_convert_encoding($value,"GBK","UTF-8");
        }
        fputcsv($fp, $row); 

    }
    fclose($fp);
    
  }



    static function img_list($upload_dir){

        if(!$upload_dir) return 'Error';

        $upload_dir=str_replace("[*]","/",$upload_dir);
        echo $upload_dir;

        $files = scandir($upload_dir);

        foreach ($files as $file) {
            $file2 = "/".$upload_dir."/".$file;
            echo $file2.",".is_file($file2)."</br/>";
            if (is_file($file2) && $file2 != '.' && $file2 != '..') {
                echo '<img src="'. $file2 . '" style="width:100px;margin-right:10px;" alt="' . $file . '"  />';
            }else{
                echo '<a href="/admin/img_list/upload_dir/'.$file2.'">'.$file."</a><br/>";
            }
        }
    }

    //删除文件
    static function rm_file($file=null){
        if(!$file) return 0;

        $files = explode(",",$file);
        $cnt=0;
        foreach($files as $file){
            $fn = public_path().$file; 
            if(is_file($fn)){
                unlink($fn);
            }
        }

        return $cnt;
    }


    //通用的上传方法
    public function upload_x(){
        $files = $_FILES;
        if(count($files)<1) return json(['code'=>0,'msg'=>'Error!']);

        $res =[];
        foreach($files as $file){
            $res[] =$this->upload($file);
        }

        return $res;
    }

    //文件上传处理
    static function upload($file=null){
        // 允许上传的图片后缀
        $allowedExts = array("gif", "jpeg", "jpg", "png","csv");
        if(!$file) $file=$_FILES['file'];

        $temp = explode(".", $file["name"]); //无参，单个文件上传
        $extension = end($temp);     // 获取文件后缀名

        if($extension!="csv" && $file["size"] > (1024*1024*2)){
            return array('code'=>0,'msg'=>"上传失败,图片文件不能超过2MB！");
        }elseif($file["size"] > (1024*1024*4)){
            return array('code'=>0,'msg'=>"上传失败,数据文件不能超过2MB！");
        }

        if ((($file["type"] == "text/csv")
        || ($file["type"] == "image/gif")
        || ($file["type"] == "image/jpeg")
        || ($file["type"] == "image/jpg")
        || ($file["type"] == "image/pjpeg")
        || ($file["type"] == "image/x-png")
        || ($file["type"] == "image/png"))
        && in_array($extension, $allowedExts)){
            if ($file["error"] > 0){
                return ['code'=>0,"msg"=> $file["error"]];
            }else{
                $msg =[];
                $msg[] = array("File name" => $file["name"]);
                $msg[] = array('File type' => $file["type"]);
                $msg[] = array('File size' => $file["size"]/1024);
                $msg[] = array('Tmp name' => $file["tmp_name"]);
                 
                // 判断当期目录下的 upload 目录是否存在该文件
                // 如果没有 upload 目录，你需要创建它，upload 目录权限为 777
                if($extension=="csv"){
                    $folder="upload/excel";
                    return ['code'=>1,'msg'=>$file["tmp_name"]];
                }else{
                    $folder="upload/".date("Ymd");
                }

                $targetPath = public_path(). $folder;

                if(!file_exists($targetPath)){
                    mkdir($targetPath,0777,1);
                    chmod($targetPath,0777);
                }

                $fn = md5($file['name'].time()).".".$extension;
                move_uploaded_file($file["tmp_name"], $targetPath."/" . $fn);
                return ['code'=>'1', 'msg'=>"/".$folder."/". $fn];
            }
        }else{
            return array('code'=>0,'msg'=>"非法的文件格式");
        }
    }

    /**
     * 验证手机号
     * @param $mobile
     * @return bool
     */
    static function is_mobile($mobile){
        if(empty($mobile)) return 0;
        if (strlen($mobile) == "11") {
            //上面部分判断长度是不是11位
            $phone_pattern = "/^1[356789]{1}\d{9}$/"; //1+[3,5,6,7,8,9]+9位数
            $n = preg_match_all($phone_pattern,$mobile);
            return $n;
        } else {
            return 0;
        }
    }


    //随机字符串
    static function randomString($length = 10) { 
      $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
      $randStr = ''; 
      for ($i = 0; $i < $length; $i++) { 
        $randStr .= $characters[rand(0, strlen($characters) - 1)]; 
      } 
      return $randStr; 
    }

    //时间美化
    public static function time_format($second=0){
        if(!$second || $second<0) return '已过期';

        $days = floor($second/3600/24);
        if($days) return $days."天";

        $hours = floor($second/3600);
        if($hours<1) $hours=0;

        $minutes  = floor(($second%3600)/60);
        if($minutes<1) $minutes =0;

        return $hours."小时".$minutes."分";

    }

    //curl_post method
    static function curl_post($url, $param){
        $curl = curl_init();
        $headers = ['Accept:application/json','Content-Type:application/json;charset=utf-8'];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_POST, true);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    //通用的放垃圾筒方法,参数：table_name,id
    public static function row_del($table,$id,$msg='Unknown',$slave_table=''){
        $all=Request::param();
        //halt($all);
        if(empty($id) || empty($table)) return json(['code'=>0,'msg'=>'无效的操作!']);     
        $row=Db::table($table)->where('id',$id)->find();
        if(empty($row)) return json(['code'=>0,'msg'=>'No found item by id.']);
        //if($row['status']!=2) return json(['code'=>0,'msg'=>'Can not remove this item!']);
        
        //backup
        Db::table('trash')->insert(['name'=>$msg,'table_name'=>$table,'data'=>json_encode($row,JSON_UNESCAPED_UNICODE),'creater'=>Session::get('logonid'),'create_time'=>date("Y-m-d H:i:s")]);
        //remove
        $res = Db::table($table)->where('id',$id)->delete();  

        if($slave_table){
            $arr=explode("|",$slave_table);
            $slave_table=$arr[0];
            $slave_tb_id=$arr[1];
            
            // $list = Db::table($slave_table)->where($slave_tb_id,$all['id'])->select()->toArray();
            // foreach($list as $specs){
            //     common::row_del('wh_list', $specs['id'], '出入库明细');
            // }
        }
        return json(['code'=>$res,'msg'=>'ok']);

    }

    //初始化系统
    public static function db_init(){
        $uid=Session::get('logonid');
        if(empty($uid) || $uid !=1) {
            return array('code'=>0,'msg'=>'没有权限！');
        }
        $arr='acc_log,allocate_log,customer,delivery,delivery_list,follow_log,goods,msg,order,order_list,order_log,specs,trash,wh_bill,wh_list';

        // $tbs=Db::query('show tables;');
        echo '开始初始化……<br />';
        echo '----------------------------<br/>';
        foreach(explode(",",$arr) as $tb){
            echo '清除数据表：'.$tb."<br/>";
            Db::execute('truncate table `'.$tb.'`');
        }
        echo '----------------------------<br/>';
        echo '完成初始化……<br />';
        echo '保留数据表：系统设置表,菜单表,产品分类表,用户表,仓库表,权限表';
        echo "<br /><br /><a href='/admin'>进入系统</a>";

    }

    static function csv_test(){
        $list = array(
            array("Peter", "Griffin", "Oslo", "Norway"),
            array("Glenn", "Quagmire", "Oslo", "Norway")
            );
            
            $file = fopen("upload/excel/contacts.csv", "w");// die("Can't Open test.csv");
            
            foreach ($list as $line) {
                fputcsv($file, $line);
            }
            
            fclose($file);

            return $file;
    }

}